package com.cjdes.recipes4u;

import com.cjdes.recipes4u.dto.Recipe;
import com.cjdes.recipes4u.dto.RecipeStore;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TableLayout;
import android.support.v4.app.NavUtils;

public class ListOfRecipes extends Activity {
	
	private String selectedRecipeType;
	private RecipeStore store;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_list_of_recipes);
		
		Bundle thisbundle = this.getIntent().getExtras();
		selectedRecipeType = (String) thisbundle.get("recipeType");
		store = (RecipeStore) thisbundle.get("recipeStore");
		setTitle(selectedRecipeType);
		TableLayout recipeLayout = (TableLayout) findViewById(R.id.recipeLayout);
		int i = 0;
		for (final Recipe recipe : store.getRecipesByType(selectedRecipeType)) {
			final Button recipeButton = new Button(this);
			recipeButton.setText(recipe.getName());
			recipeButton.setId(i);
			recipeButton.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(ListOfRecipes.this, DisplayRecipe.class);
					Bundle bundle = new Bundle();
					bundle.putSerializable("recipeName", recipe.getName());
					bundle.putSerializable("recipeStore", store);
					intent.putExtras(bundle);
					startActivity(intent);
				}
			});
			recipeLayout.addView(recipeButton);
			
		}
		getActionBar().setDisplayHomeAsUpEnabled(true);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_list_of_recipes, menu);
		getMenuInflater().inflate(R.menu.header, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case android.R.id.home :
				NavUtils.navigateUpFromSameTask(this);
				return true;
			case R.id.action_refresh:
				Intent i = new Intent();
                i.setClass(ListOfRecipes.this, MainActivity.class);
                i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);
				return true;
			default: 
				return super.onOptionsItemSelected(item);
			}
		}

	public String getSelectedRecipeType() {
		return selectedRecipeType;
	}

	public void setSelectedRecipeType(String selectedRecipeType) {
		this.selectedRecipeType = selectedRecipeType;
	}
	public void setStore(RecipeStore store) {
		this.store = store;
	}
	public RecipeStore getStore() {
		return store;
	}

}
